<template>
  <d2-container>
  <div class="app-container">
    <el-container :style="search?'height:'+containerHeight+'px':''">
      <el-main>
        <el-row>
          <div class="search-area">
            <el-form label-position="right" :model="dataForm" :inline="true">
              <div style="font-size:15px;display:inline-block; float:left;">
                <el-form-item label="分类" label-width="40px">
                  <el-select v-model="dataForm.energyType"  style="width: 100px;" placeholder="请选择"  size="mini">
                    <el-option
                      v-for="(item, index) in meterTypeList" :key="index"
                      :label="item.paramValue"
                      :value="item.paramKey">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="日期" label-width="40px" v-if="search">
                    <el-date-picker
                      v-model="dataForm.date"
                      placeholder="时间范围"
                      style="width: 250px;"
                      class="filter-item"
                      size="mini"
                      :type="dataForm.dateType"
                      suffix-icon="el-icon-date"
                      clearable
                      @keyup.enter.native="getPowerDataList"
                    >
                    </el-date-picker>
                </el-form-item>
              </div>
              <div style="display:inline-block; ">
                <el-form-item>
                  <el-button v-if="search"
                    class="filter-item"
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="getPowerDataList"
                  >查询</el-button>
                  <el-button
                      class="filter-item"
                      type="primary"
                      icon="el-icon-download"
                      size="mini"
                      @click="exoprtData"  v-if="search"
                  >导出</el-button>
                </el-form-item>
              </div>
            </el-form>
          </div>
        </el-row>
        <div style="margin-top:20px;">
          <el-row>
            <el-col :span="24">
              <el-table :data="dataList" :height="search?chartHeight:''" border style="width: 100%;overflow:auto;">
                <!-- <el-table-column prop="index" header-align="center" align="center"  width="70" label="序号"></el-table-column> -->
                <el-table-column
                  prop="orgName"
                  header-align="center"
                  align="center"
                  label="部门"
                ></el-table-column>
                <el-table-column
                  prop="meterTypeName"
                  header-align="center"
                  align="center"
                  label="分类"
                  width="70"
                ></el-table-column>
                <el-table-column
                  prop="date"
                  header-align="center"
                  align="center"
                  label="时间"
                ></el-table-column>
                <el-table-column
                  prop="val"
                  header-align="center"
                  align="center"
                  :label="`用量(${unit})`"
                ></el-table-column>
              </el-table>
              <el-pagination v-if="search"
                class="mt-4"
                @size-change="sizeChangeHandle"
                @current-change="currentChangeHandle"
                :current-page="page.page"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="page.size"
                :total="page.total"
                layout="total, sizes, prev, pager, next, jumper">
              </el-pagination>
            </el-col>
          </el-row>
        </div>
      </el-main>
    </el-container>
  </div>
  </d2-container>
</template>

<script>
import * as Util from "@/utils";
import * as Echarts from 'echarts'
import Config from "@/utils/config"
import Minix from '../power/mixin'
export default {
  name: "areaPage",
  mixins:[Minix],
  props:{
    search:{
      type:Boolean,
      default:true
    }
  },
  data() {
    return {
      Config:Config,
      activeName:'2',
      dataForm: {
        date:new Date(),
        dateType:'month',
        energyType:this.$meterType.ELECTRIC,
      },
      page: {
        page: 1,
        total: 0,
        size: 10
      },
      buildTreeProps: {
        label: "buildingName",
        children: "children"
      },
      orgTreeProps: {
        label: "organizationName",
        children: "children"
      },
      unit:'',
      dataList:[],
      dataBuildingList: [],
      dataOrgList:[],
      meterTypeList:[],
      currentSelectBuildInfoList:[],
      currentSelectDepartInfoList:[],
      departTableDataList:[],
      sourceData:[],
    };
  },
  computed: {
    containerHeight() {
      return Util.getClientHeight() - 143;
    },
    chartHeight(){
       return Util.getClientHeight() - 325;
    }
  },
  created() {
    this.queryStatic("METER_TYPE");
    this.getDepartList();
    this.getBuildInfoList();
  },
  methods: {
    sizeChangeHandle(size){
      this.page.size = size;
      this.handleDataList();
    },
    currentChangeHandle(page){
      this.page.page = page;
      this.handleDataList();
    },
    exoprtData(){
      let header=['部门','分类','时间',`用量(${this.unit})`];
      let props=['orgName','meterTypeName','date','val'];
      let fileName=`用${this.meterTypeList.find(item=>item.paramKey==this.dataForm.energyType).paramValue}统计`;
      this.export2Excel(header,props,fileName,this.sourceData)
    },
    export2Excel (tH, fi, fiNa, dataList) {
      var tHeader = tH
      var filterVal = fi
      var fileName = fiNa
      require.ensure([], () => {
        const {export_json_to_excel} = require('@/utils/Export2Excel.js')
        const list = dataList
        const data = this.formatJson(filterVal, list)
        export_json_to_excel(tHeader, data, fileName)
      })
    },
    //选中部门
    selectDepart(){
      this.currentSelectDepartInfoList = this.$refs.departTree.getCheckedNodes();
    },
    //选中设备
    selectBuild(){
      this.currentSelectBuildInfoList = this.$refs.buildTree.getCheckedNodes();
    },
    // 获取区域树
    getBuildInfoList() {
      this.$api.okhttp({
        url: this.$http.adornUrl("/ecs/ecsbuildinginfo/select"),
        method: "get",
        params: this.$http.adornParams({
          'page': 1,
          'limit': 10000,
          customerId: this.$util.cookies.get("customer_id"),
          projectid:this.$util.cookies.get("cuuren_projectId")
        })
      }).then((data) => {
        if (data && data.code === 0) {
          this.dataBuildingList =  Util.treeDataTranslate(
            data.menuList,
            "buildingId",
            "parentBuildingId"
          );
        } else {
          this.dataBuildingList = [];
        }
      });
    },
    // 获取部门数据列表
    getDepartList () {
      this.$api.okhttp({
        url: this.$http.adornUrl("/ecs/ecsorganizationinfo/select"),
        method: 'get',
        params: this.$http.adornParams({
          'page': 1,
          'limit': 10000,
          "customerId":this.$util.cookies.get('customer_id')
        })
      }).then((data) => {
        if (data && data.code === 0) {
          this.dataOrgList =Util.treeDataTranslate(data.menuList,'organizationId','parentOrgId')
        } else {
          this.dataOrgList = []
        }
      })
    },
    /**
     * 获取参数枚举
     */
    queryStatic(type) {
      this.$api.okhttp({
        url: this.$http.adornUrl('/sys/sysstaticdata/getList'),
        method: 'get',
        params: this.$http.adornParams({
          'code': type ,
          "customerId":this.$util.cookies.get('customer_id')
        })
      }).then((data) => {
        if (data && data.code === 0) {
          this.meterTypeList = data.page
          this.dataForm.energyType = data.page[0].paramKey;
          this.unit = data.page[0].paramExt;
        } else {
          this.meterTypeList = []
        }
        this.getPowerDataList();

      });
    },
    getPowerDataList() {
      this.sourceData = [];
      this.dataList = [];
      let currentSelectInfo = [];
      let params = {
          customerId: this.$util.cookies.get("customer_id"),
          meterType:this.dataForm.energyType , //能耗分类
          date:new Date(this.dataForm.date).format('yyyy-MM'), //日期
      }
      this.$api.okhttp({
        url: this.$http.adornUrl('/ecm/depart/show'),
        method: 'post',
        data: this.$http.adornData(params)
      }).then((data) => {
        if (data && data.code === 0) {
          //console.log('所有数据',data.data)
          if(data.data&&data.data.length>0){
            this.sourceData =data.data;
            if(this.sourceData.length>0){
              this.page.total = this.sourceData.length;
              this.sourceData.forEach(ele=>{
                ele.meterTypeName = this.meterTypeList.find(item=>item.paramKey==this.dataForm.energyType).paramValue;
              })
            }
            else{
              this.page.total =0;
              this.dataList = [];
            }
            this.handleDataList()
          }
        }
      });
    },
    handleDataList(){
      if(this.sourceData.length>0){
        let totalPage = Math.ceil(this.sourceData.length/this.page.size);
        if(this.page.page<=totalPage){
          if(this.page.page*this.page.size>=this.sourceData.length){
             this.dataList = this.sourceData.slice((this.page.page-1)*this.page.size,this.sourceData.length);
          }
          else{
            this.dataList = this.sourceData.slice((this.page.page-1)*this.page.size,this.page.page*this.page.size);
          }
        }
      }
    }
  },
  watch:{
    'dataForm.energyType':function(newV,oldV){
      this.unit = this.meterTypeList.find(item => item.paramKey == newV).paramExt;
    },
  }
};
</script>

<style scoped>
.tree-area { background-color: rgba(0, 0, 0, 0.1);
  width: 250px !important;
  /* box-shadow: 0px 0px 2px 2px #f7f6f6; */
  /* border: solid 1px #808080; */
  padding-top: 10px;
  padding-left: 15px;
}
.bg-white {
  box-shadow: 0px 0px 2px 2px #f7f6f6;
}
.el-tree-node__content {
  height: 30px !important;
}
.busi-chart{
    width: 100%;
    height: 250px;
    margin-top: 10x;
    margin-bottom: 20px;
}
.el-form-item{
  margin-bottom: 0px;
}
.search-area{
   display:flow-root;
   margin-bottom: 10px;
   border: 1px solid #808080;
   border-left: none;
   border-right: none;
   padding: 10px 0px 10px 0px;
}
</style>
